<?php
/**
 * Created by PhpStorm.
 * User: fengdh
 * Date: 2019/7/29
 * Time: 15:11
 */

namespace search\controllers;

use business\elasticsearch\models\SupplierModel;
use common\utils\AreaAnalyzerUtils;
use Elasticsearch\ClientBuilder;
use yii\elasticsearch\Query;
use yii\web\Controller;
use linslin\yii2\curl\Curl;

class TestController extends Controller
{
    public function actionTest()
    {
        $model = new SupplierModel();
//        $data = $model::find()->asArray()->all();

        $query = [
            "bool" => [
//                "filter" => [
//                    "range" => [
//                        "id" => [
//                            "from" => 3,
//                            "to" => 4
//                        ]
//                    ]
//                ],
              "filter" => [
                    "term" => [
                        "regLocationCode" => '85',
                    ]
                ],
//                "must" => [
//                    ["match" => ["regLocationCity"=>"广东"]],
//                    ["match" => ["serviceLocationCode"=>231]],
//                    ["match" => ["companyName"=>'惠州市第一建筑工程有限公司']],
//                    ['match' => ['basicCategoryName' => ['query' => 'LED屏工程', 'boost' => 10]]]
//                ],
//                'should' => [
//                    ['match' => ['companyName' => ['query' => '建筑工程有限公司']]],
//                    ['match' => ['from' => ['query' => 'test2']]],
//                    ['match' => ['url' => ['query' => 'www.yunlian.com', 'boost' => 10]]]
//                ],
            ],
        ];
//        $query = [
//            'bool' => [
//                "must" => [
//                    ["match_phrase" => ["companyName"=>'惠州市第一建筑工程有限公司']],
//                ]
//            ]
//        ];
//        $query = [
//            'bool' => [
//                "must" => [
//                    ["terms" => ["serviceLocationCode"=>[231,222]]],
//                ]
//            ]
//        ];
//        $highlight = [
//            'pre_tags' => ['<span class="highlight">'],
//            'post_tags' => ['</span>'],
//            "fields"=>[
//                "name"=>new \stdClass(),
//                'url'=>new \stdClass()
//            ]
//        ];
//        $sort = ['id' => ['order' => 'desc']];

        $aggs = ['popular_colors' => ['terms' => ['field' => 'serviceLocationName.keyword']]];
        $search = [
            'size' => 0,
            'query' => $query,
            'aggs' => $aggs,
        ];
        $query = $model::find()->createCommand();
        $query->queryParts = $search;
        $data = $query->search();


//        $data = $model::find()
//            ->query($query)
//            ->count();
//            ->highlight($highlight)
//            ->orderBy($sort)
//            ->asArray()
//            ->all();

//        $data = SupplierModel::findOne('G000004');
//        $model->primaryKey = 'G12347';
//        $model->name = '明源云空间';
//        $model->url = 'www.yunkongjian.com';
//        $model->address = '创维大厦3楼';
//        $model->from = ['test1', 'test2'];
//        $model->to = 'to_test';
//        $data = $model->save();

//        $data = SupplierModel::deleteAll(['_id'=>5]);
        var_dump($data);exit;
    }

    public function actionIndex()
    {
        $client = ClientBuilder::create()->setHosts([
            [
                'host'   => 'es-cn-45916vpe5000m25am.public.elasticsearch.aliyuncs.com',
                'port'   => '9200',
                'scheme' => 'http',
                'user'   => 'elastic',
                'pass'   => 't$Ideov5yhaCpc4b'
            ]
        ])->setConnectionPool('\Elasticsearch\ConnectionPool\SimpleConnectionPool', [])
            ->setRetries(10)->build();
//        $params = [
//            'index'  => 'supplier',
//            'type'   => 'my_type',
//            'id'     => '2',
//            'body'   => ['name' => '明源云链','id'=>2,'url'=>'www.mycaigou.com'],
//            'client' => [
//                'timeout'         => 10,
//                'connect_timeout' => 10
//            ]
//        ];
//        $result = $client->index($params);
//        var_dump($result);

        $params = [
            'index' => 'supplier',
            'type' => 'my_type',
            'body' => [
                'query' => [
                    'match' => [
                        'name' => '云链'
                    ]
                ]
            ]
        ];


        $response = $client->search($params);
        print_r($response);
        exit;
    }

    public function actionAnalyzer(){
        
        $type = \Yii::$app->request->get('type');
        $analyzer = \Yii::$app->request->get('analyzer', '');
        if($type == 'keyword') {
            $keyword = \Yii::$app->request->get('keyword');
            $rs = $this->getEsAnalyzer($keyword);
            print_r($rs);
        }elseif($type == 'category') {
            $list = $this->getCategory();
            foreach ($list as $key => $item) {
                $rs = $this->getEsAnalyzer($item['category_name']);

                if (!empty($rs)) {
                    $data      = json_decode($rs, true);
                    $sub_words = array();
                    if (array_key_exists('tokens', $data)) {
                        $sub_words = array_column($data['tokens'], 'token');
                    }

                    $list[$key]['sub_words'] = $sub_words;
                } else {
                    $list[$key]['sub_words'] = [];
                }
            }
            print_r($list);
        }
    }
    
    private function getEsAnalyzer($keyword, $analyzer = 'ik_max_word'){
        $url = 'http://es-cn-45916vpe5000m25am.public.elasticsearch.aliyuncs.com:9200/_analyze';
        $auth = 'elastic:t$Ideov5yhaCpc4b';
        $param = array(
            "analyzer" => $analyzer,
            'text'     => $keyword
        );

        return $this->request_post($url, $param, $auth);
    }

    private function getCategory(){
        return (new \yii\db\Query())
            ->from('b2b_parameter.bsp_basic_forest')
            ->select('category_name')
            ->where(['hierarchy_level' => 3,'category_status' => 1])
            ->createCommand(\Yii::$app->db)
            ->queryAll();
    }

    private function request_post($url, $data = null, $auth = '', $options=null)
    {
        $curl = new Curl();
        if(!empty($options))
        {
            foreach($options as $key=>$value)
            {
                $curl->setOption($key, $value);
            }
        }
//        curl_setopt($curl, CURLOPT_USERPWD, $auth);
        $curl->setOption(CURLOPT_USERPWD, $auth);
        $curl->setOption(CURLOPT_HTTPHEADER, ['content-type: application/json']);
        $curl->setOption(CURLOPT_TIMEOUT, 60);

        $curl->setOption(CURLOPT_SSL_VERIFYPEER, FALSE);
        $curl->setOption(CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)){
            $curl->setOption(CURLOPT_POST, 1);
            $dataUrl = '';
            if(is_array($data)){
                $dataUrl = json_encode($data, JSON_UNESCAPED_UNICODE);
            }else{
                $dataUrl = $data;
            }
            $curl->setOption(CURLOPT_POSTFIELDS, $dataUrl);
        }
        return  $curl->post($url);
    }

    public function actionAreaAnalyzer()
    {
        $str = "四川省防水电力有限公司";
        $res = AreaAnalyzerUtils::tokenizer($str);
        $ret = array_values(array_column($res,'token'));
        echo implode(' ',$ret);
        print_r($ret);
    }

    private function request($url, $type, $data = false, $header = [], $timeout = 10)
    {
        $ch = curl_init();
        // 兼容HTTPS
        if (stripos($url, 'https://') !== FALSE) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSLVERSION, 1);
        }
        // 设置返回内容做变量存储
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 设置需要返回Header
        curl_setopt($ch, CURLOPT_HEADER, true);
        // 设置请求头
        if (count($header) > 0) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        // 设置需要返回Body
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        // 设置超时时间
        if ($timeout > 0) {
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        }
        // POST/GET参数处理
        $type = strtoupper($type);
        if ($type == 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            if(in_array('Content-Type:application/x-www-form-urlencoded', $header)){
                $data = http_build_query($data);
            }
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        if ($type == 'GET' && is_array($data)) {
            if (stripos($url, "?") === FALSE) {
                $url .= '?';
            }
            $url .= http_build_query($data);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        // 读取获取内容
        $response = curl_exec($ch);
        // 读取状态
        $status = curl_getinfo($ch);
        // 读取错误号
        $errno = curl_errno($ch);
        // 读取错误详情
        $error = curl_error($ch);
        // 关闭Curl
        curl_close($ch);
        if ($errno == 0 && isset($status['http_code'])) {
            $header = substr($response, 0, $status['header_size']);
            $body   = substr($response, $status['header_size']);
            return array(
                'content' => $body,
                'header' =>$header,
                'status' => $status,
                'errno' => 0,
                'error' => ''
            );
        } else {
            return array(
                'content' => '',
                'header' =>'',
                'status' => $status,
                'errno' => $errno,
                'error' => $error
            );
        }
    }
}